<?php
/**
 * PHP version 7.1+
 *
 * @copyright  Copyright (c) 2012-2015 EELLY Inc. (http://www.eelly.com)
 * @link       http://www.eelly.com
 * @license    衣联网版权所有
 */

if (!function_exists('isMobile')) {
    /**
     * 判断是否是手机号码
     * @param $mobile
     * @return bool
     * @since 2017/06/10 22:45:56
     */
    function isMobile($mobile): bool
    {
        $mobile = trim($mobile);
        if (strlen($mobile) < 1) {
            return false;
        }
        $pattern = "/^1[34578]\d{9}$/";
        if (preg_match($pattern, $mobile)) {
            return true;
        } else {
            return false;
        }
    }
}


if (!function_exists('isEmail')) {
    /**
     * 是否是邮箱
     * @param $email
     * @return bool
     * @since 2017/06/10
     */
    function isEmail($email): bool
    {
        $email = trim($email);
        if (strlen($email) < 1) {
            return false;
        }
        $pattern = "/^([0-9A-Za-z\\-_\\.]+)@([0-9a-z]+\\.[a-z]{2,3}(\\.[a-z]{2})?)$/i";
        if (preg_match($pattern, $email)) {
            return true;
        } else {
            return false;
        }
    }
}

if (!function_exists('arrayToHump')) {
    /**
     * 数组转驼峰.
     *
     * @param array $data 等待转换的数组
     *
     * @return array 返回转驼峰之后的数组
     *
     * @since 2017-8-23
     */
    function arrayToHump(array &$data)
    {
        if (empty($data)) {
            return [];
        }
        if (is_array($data)) {
            foreach ($data as $key => $value) {
                $key = preg_replace_callback('/(_)([a-z])/i', function ($matches) use (&$data, &$key) {
                    unset($data[$key]);

                    return ucfirst($matches[2]);
                }, $key);
                $temp[$key] = $value;
                if (is_array($value)) {
                    $temp[$key] = arrayToHump($value);
                }
            }
        }
        return $temp;
    }
}

if (!function_exists('formatJqGrid')) {
    /**
     * 转化为JqGrid识别的数据.
     *
     * @param array $data 等待转换的数组
     *
     * @return string "0:111,2:222"
     *
     * @since 2018年12月20日
     */
    function formatJqGrid(array $data): string
    {
        !is_array($data) && $data = [];
        $str = '';
        foreach ($data as $key => $value) {
            !empty($str) && $str .= ';';
            $str .= $key . ":" . $value;
        }
        return $str;
    }
}


if (!function_exists('createUuid')) {
    /**
     * 创建uuid.
     *
     *
     * @return string
     *
     * @since 2018年12月20日
     */
    function createUuid(): string
    {

        try {
            $uuid = (\Ramsey\Uuid\Uuid::uuid1())->toString();
        } catch (\Ramsey\Uuid\Exception\UnsatisfiedDependencyException $exception) {
            createUuid();
        }
        return $uuid;
    }
}

if (!function_exists('strReplaceOnce')) {

    //只替换一次
    /**
     * strReplaceOnce.
     *
     * @param string $needle 需要被替换的
     * @param string $replace 替换后的值
     * @param string $content 现在的内容
     * @return mixed
     * @author 肖俊明<2284876299@qq.com>
     * @since 2019年06月14日
     */
    function strReplaceOnce($needle, $replace, $content)
    {
        $pos = strpos($content, $needle);
        if ($pos === false) {
            return $content;
        }
        return substr_replace($content, $replace, $pos, strlen($needle));
    }
}

if (!function_exists('dateToStartOrEndTime')) {

    /**
     * 转化为开始或者结束时间.
     *
     * @param $startTime
     * @param bool $end
     * @return false|int
     * @author 肖俊明<2284876299@qq.com>
     * @since 2020年03月17日
     */
    function dateToStartOrEndTime($startTime, $end = false)
    {
        $staticTime = strtotime('1970-01-01 00:00:00');
        $startTimeInt = strtotime($startTime);
        if ($staticTime >= $startTimeInt) {
            return 0;
        }
        $startTime = strtotime(date('Y-m-d 00:00:00', $startTimeInt));
        return $end == false ? $startTime : $startTime + 86399;
    }
}


if (!function_exists('createOrderSn')) {
    /**
     * 创建uuid.
     *
     *
     * @return string
     *
     * @since 2018年12月20日
     */
    function createOrderSn($userId, $goodsId): string
    {

        $dateTime = date('YmdHis');
        //两位是用户ID的
        $createUserId = (string)substr((string)$userId, -2);
        strlen($createUserId) <= 1 && $createUserId = '0' . $createUserId;
        //两位是商品的
        $createGoodsId = (string)substr((string)$goodsId, -2);
        strlen($createGoodsId) <= 1 && $createGoodsId = '0' . $createGoodsId;


        try {
            $orderSn = $dateTime . random_int(1000, 9999) . $createUserId . $createGoodsId;
        } catch (\Ramsey\Uuid\Exception\UnsatisfiedDependencyException $exception) {
            createOrderSn();
        }
        return $orderSn;
    }
}


if (!function_exists('getWeek')) {

    /**
     * get_week.
     *
     * @param $date
     * @return mixed
     * @author 肖俊明<2284876299@qq.com>
     * @since 2020年02月20日
     */
    function getWeek($date)
    {
        //强制转换日期格式
        $date_str = date('Y-m-d', strtotime($date));

        //封装成数组
        $arr = explode("-", $date_str);

        //参数赋值
        //年
        $year = $arr[0];

        //月，输出2位整型，不够2位右对齐
        $month = sprintf('%02d', $arr[1]);

        //日，输出2位整型，不够2位右对齐
        $day = sprintf('%02d', $arr[2]);

        //时分秒默认赋值为0；
        $hour = $minute = $second = 0;

        //转换成时间戳
        $strap = mktime($hour, $minute, $second, $month * 1, $day * 1, $year * 1);

        //获取数字型星期几
        $number_wk = date("w", $strap);

        //自定义星期数组
        $weekArr = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"];

        //获取数字对应的星期
        return $weekArr[$number_wk];
    }

}



if (!function_exists('getWechatImageUrl')) {

    /**
     * 获取微信图片所要上传的url.
     *
     * @param $wechatImgUrl
     * @return string
     * @author 肖俊明<2284876299@qq.com>
     * @since 2020年03月31日
     */
    function getWechatImageUrl($wechatImgUrl,$defaultExtension = "jpg")
    {
        $imageItem = parse_url($wechatImgUrl);



        try {
            list(,$ext) = explode('=',$imageItem['query']);
            if (strrpos($ext, "?") !== false) {
                $ext = substr($ext, 0, strpos($ext, '?'));
            }
        } catch (\Exception $exception) {
            $ext = $defaultExtension;
        }


        empty($ext) && $ext = $defaultExtension;

        $fileName = pathinfo($imageItem['path'])['dirname'];
        return sprintf("uploads%s.%s",$fileName,$ext);
    }

}


if (!function_exists('getVideoImageUrl')) {

    /**
     * 获取视频所要上传的url.
     *
     * @param $imgUrl
     * @return string
     * @author 肖俊明<2284876299@qq.com>
     * @since 2020年03月31日
     */
    function getVideoImageOrMp4Url(string $imgUrl, $defaultExtension = ".jpg")
    {
        try {
            $imageItem = parse_url($imgUrl);

            $pathInfo = pathinfo($imageItem['path']);
            $fileName = $pathInfo['basename'];
            $extensionArr = [
                'gif', 'jpg', 'bmp', 'png', 'jpeg',
                'mp4', 'avi', 'divx', 'dat', 'mpeg4', 'vcd', 'mpeg1', 'mpeg2', 'dvd', 'vob', 'rm', 'rmvb', 'wmv', 'asf'
            ];
            (empty($pathInfo['extension']) ||
                !in_array($pathInfo['extension'], $extensionArr)) && $fileName .= $defaultExtension;
            return sprintf("video/%s", $fileName);
        } catch (\Exception $exception) {
            return '';
        }
    }

}

if (!function_exists('getCommonImageUrl')) {

    /**
     * 获取视频所要上传的url.
     *
     * @param $imgUrl
     * @return string
     * @author 肖俊明<2284876299@qq.com>
     * @since 2020年03月31日
     */
    function getCommonImageUrl(string $imgUrl, $defaultExtension = ".jpg")
    {
        try {
            $imageItem = parse_url($imgUrl);

            $pathInfo = pathinfo($imageItem['path']);
            $fileName = $pathInfo['basename'];
            $extensionArr = [
                'gif', 'jpg', 'bmp', 'png', 'jpeg',
                'mp4', 'avi', 'divx', 'dat', 'mpeg4', 'vcd', 'mpeg1', 'mpeg2', 'dvd', 'vob', 'rm', 'rmvb', 'wmv', 'asf','mp3',
                'm4a'
            ];
            (empty($pathInfo['extension']) ||
                !in_array($pathInfo['extension'], $extensionArr)) && $fileName .= $defaultExtension;
            return sprintf("uploads/%s", $fileName);
        } catch (\Exception $exception) {
            return '';
        }
    }

}


if (!function_exists('getWechatVideoUrl')) {

    /**
     * 获取微信图片所要上传的url.
     *
     * @param $wechatImgUrl
     * @param $defaultExtension
     * @return string
     * @author 肖俊明<2284876299@qq.com>
     * @since 2020年03月31日
     */
    function getWechatVideoUrl($wechatVideoUrl, $defaultExtension = "mp4")
    {
        $videoItem = parse_url($wechatVideoUrl);

        $pathInfo = pathinfo($videoItem['path']);

        $fileName = md5($wechatVideoUrl);

        $extensionArr = ['mp4', 'avi', 'divx', 'dat', 'mpeg4', 'vcd', 'mpeg1', 'mpeg2', 'dvd', 'vob', 'rm', 'rmvb', 'wmv', 'asf'];


        if (empty($pathInfo['extension']) ||
            !in_array($pathInfo['extension'], $extensionArr)) {
            $ext = $defaultExtension;
        } else {
            $ext = $pathInfo['extension'];
        }
        return sprintf("uploads/%s.%s",$fileName,$ext);
    }

}

if (!function_exists('getWechatAudioUrl')) {

    /**
     * 获取微信图片所要上传的url.
     *
     * @param $wechatImgUrl
     * @param $defaultExtension
     * @return string
     * @author 肖俊明<2284876299@qq.com>
     * @since 2020年03月31日
     */
    function getWechatAudioUrl($audioId, $defaultExtension = "mp3")
    {
        return sprintf("uploads/%s.%s",$audioId,$defaultExtension);
    }

}


if (!function_exists('getUrlInContent')) {


    /**
     * 在内容中获取连接地址.
     *
     * @param $content
     * @return string
     * @author 肖俊明<2284876299@qq.com>
     * @since 2020年04月14日
     */
    function getUrlInContent($content)
    {
        try {
            $reg = '/(http|https)(.)*([A-Za-z0-9\-\.\_])+/i';
            preg_match($reg, $content, $match);
            $uri = $match[0];
            $str = strstr($uri,' ');
            !empty($str) && $uri = str_replace($str,'',$uri);
            return $uri;
        } catch (Exception $exception) {
            return '';
        }
    }
}

if (!function_exists('remoteFileSize')) {

    /**
     * remoteFileSize.
     *
     * @param $url
     * @param string $user
     * @param string $pw
     * @return int
     * @author 肖俊明<2284876299@qq.com>
     * @since 2020年04月04日
     */
    function remoteFileSize($url, $user = "", $pw = "")
    {
        ob_start();
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_HEADER, 1);
        curl_setopt($ch, CURLOPT_NOBODY, 1);

        if(!empty($user) && !empty($pw))
        {
            $headers = array('Authorization: Basic ' .  base64_encode("$user:$pw"));
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        }

        curl_exec($ch);
        curl_close($ch);
        $head = ob_get_contents();
        ob_end_clean();

        $regex = '/Content-Length:\s([0-9].+?)\s/';
        preg_match($regex, $head, $matches);
        return isset($matches[1]) ? $matches[1] : 0;
    }
};


if (!function_exists('uploadheadimgurl')) {
    /**
     * 上传封面图.
     *
     * @param $headimgurl
     * @return string
     * @author 肖俊明<2284876299@qq.com>
     * @since 2020年04月20日
     */
    function uploadheadimgurl($headimgurl)
    {
        $fileName = '/uploads/head/'.md5($headimgurl).'.png';
        if (!Storage::put($fileName, file_get_contents($headimgurl))) {
            return $headimgurl;
        }
        return getOssUrl($fileName);
    }
}



/**
 * 发起http post请求(REST API), 并获取REST请求的结果
 * @param string $url
 * @param string $param
 * @return - http response body if succeeds, else false.
 */
function request_post($url = '', $param = '')
{
    if (empty($url) || empty($param)) {
        return false;
    }

    $postUrl = $url;
    $curlPost = $param;
    // 初始化curl
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $postUrl);
    curl_setopt($curl, CURLOPT_HEADER, 0);
    // 要求结果为字符串且输出到屏幕上
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    // post提交方式
    curl_setopt($curl, CURLOPT_POST, 1);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);
    // 运行curl
    $data = curl_exec($curl);
    curl_close($curl);

    return $data;
}


if (!function_exists('decryptEqh')) {

    /**
     * 易企秀编译的代码解析.
     *
     * @param $password
     * @return mixed
     * @author 肖俊明<2284876299@qq.com>
     * @since 2020年09月03日
     */
    function decryptEqh($password)
    {
        $key = $iv = substr($password, 19, 16);

        $password = substr($password, 0, 19) . substr($password, 19 + 16);

        $password = base64_decode($password);

        $decrypted = openssl_decrypt($password, 'aes-128-cfb', $key, OPENSSL_NO_PADDING, $iv);

        return json_decode(trim($decrypted), true);
    }

}


if (!function_exists('getEqxiuImgUrl')) {

    /**
     * 获取视频所要上传的url.
     *
     * @param $imgUrl
     * @return string
     * @author 肖俊明<2284876299@qq.com>
     * @since 2020年03月31日
     */
    function getEqxiuImgUrl(string $imgUrl, $defaultExtension = ".svg")
    {
        try {
            $imageItem = parse_url($imgUrl);

            $pathInfo = pathinfo($imageItem['path']);
            $fileName = $pathInfo['basename'];
            $extensionArr = [
                'gif', 'jpg', 'bmp', 'png', 'jpeg',
                'mp4', 'avi', 'divx', 'dat', 'mpeg4', 'vcd', 'mpeg1', 'mpeg2', 'dvd', 'vob', 'rm', 'rmvb', 'wmv', 'asf','svg'
            ];
            (empty($pathInfo['extension']) ||
                !in_array($pathInfo['extension'], $extensionArr)) && $fileName .= $defaultExtension;
            return sprintf("eqxiu/%s", $fileName);
        } catch (\Exception $exception) {
            return '';
        }
    }

}

if (!function_exists('getEqxiuAudioUrl')) {

    /**
     * 获取视频所要上传的url.
     *
     * @param $imgUrl
     * @return string
     * @author 肖俊明<2284876299@qq.com>
     * @since 2020年03月31日
     */
    function getEqxiuAudioUrl(string $audioUrl, $defaultExtension = ".mp3")
    {
        try {
            $audioItem = parse_url($audioUrl);

            $pathInfo = pathinfo($audioItem['path']);
            $fileName = $pathInfo['basename'];
            $extensionArr = [
                "mp3", "wav"
            ];
            (empty($pathInfo['extension']) ||
                !in_array($pathInfo['extension'], $extensionArr)) && $fileName .= $defaultExtension;
            return sprintf("eqxiu/%s", $fileName);
        } catch (\Exception $exception) {
            return '';
        }
    }
}


if (!function_exists('getOssUrl')) {

    /**
     * 获取视频所要上传的url.
     *
     * @param string $path
     * @param string $disks
     * @return string
     * @author 肖俊明<2284876299@qq.com>
     * @since 2020年03月31日
     */
    function getOssUrl(string $path, $disks='oss')
    {
        $downloadConfig = config('filesystems.disks.'.$disks);
        $img = Storage::disk($disks)->url($path);
        $cdnOss = $downloadConfig['cdnDomain'];
        $cdnRealDomain = $downloadConfig['cdnRealDomain'];
        return str_replace($cdnOss,$cdnRealDomain,$img);
    }
}


if (!function_exists('getOssDownloadUrl')) {

    /**
     * 获取视频所要上传的url.
     *
     * @param $url
     * @param string $title
     * @param string $disks
     * @return string
     * @author 肖俊明<2284876299@qq.com>
     * @since 2020年03月31日
     */
    function getOssDownloadUrl($url, $title = '', $disks = 'download')
    {

        $downloadConfig = config('filesystems.disks.'.$disks);
        //$cdnRealDomain = $downloadConfig['cdnRealDomain'];

        $object = trim(parse_url($url)['path'],'/');
        $newFileName = $object;

        if (!empty($title)){
            try{
                $newFileName = $title.'.'.pathinfo($url)['extension'];
            }catch (Exception $exception){
            }
        }

        /**@var $adapter \League\Flysystem\AdapterInterface*/
        $adapter = Storage::disk($disks)->getDriver()->getAdapter();
        $bucket = $adapter->getBucket();
        $options = [
            'sub_resource' => 'response-content-disposition=attachment%3Bfilename%3D'.$newFileName
        ];

        $url =  $adapter->getClient()->signUrl($bucket,$object,3600,'GET',$options);
        $cdnOss = $downloadConfig['cdnDomain'];
        $cdnRealDomain = $downloadConfig['cdnRealDomain'];
        return str_replace($cdnOss,$cdnRealDomain,$url);
    }
}












